<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use DateTimeInterface;

class Sys_Role extends Model
{
    use HasFactory;
    /**
     * 关联到模型的数据表
     *
     * @var string
     */
    protected $table = 'sys_role';


    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    protected $fillable = [
        'mec_id',
        'role_name',
        'desc',
        'menu_ids',
        'permissions',
        'is_super',
        'is_del'
    ];

    public function scopeNodel($query)
    {
        return $query->where('is_del', 'N');
    }

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format($this->dateFormat ?: 'Y-m-d H:i:s');
    }

    public function manyMechanism()
    {
        return $this->belongsToMany('App\Models\Cms_Mechanism', 'sys_roles_mechanism', 'role_id', 'mec_id');
    }

    public static function convertTrees($_permission, $parent_id = 0)
    {

        $arr = [];
        foreach ($_permission as $item) {

            if ($item['parent_id'] == $parent_id) {
                $newitem = self::convertTrees($_permission, $item['id']);
                if ($newitem) {
                    $newarr = $newitem;
                    $arr[$item['code']] = $newarr;
                } else {
                    $arr[] = $item['code'];
                }
            }
        }

        return $arr;
    }

    public static function getFilter($filter)
    {
        return self::whereHas('manyMechanism', function ($mquery) use ($filter) {
            $mquery->where('mec_id', $filter['mec_id']);
        })->where(function ($query) use ($filter){
            if (isset($filter['mec_id']) && !empty($filter['mec_id'])) {
                $query->where('mec_id', $filter['mec_id']);
            }
            if (isset($filter['role_name']) && !empty($filter['role_name'])) {
                $query->where('role_name', 'LIKE','%'.$filter['role_name'].'%');
            }
        })->orderBy('id', 'asc');
    }
}
